<template>
  <div>
    <el-tree
      ref="refTree"
      node-key="id"
      show-checkbox
      default-expand-all
      check-strictly
      :data="list"
      :props="{label: 'name'}"
    />

    <el-button @click="hClose">取 消</el-button>
    <el-button type="primary" @click="hSubmit">确 定</el-button>
  </div>
</template>

<script>
import { getPermissionList } from '@/api/permissions'
import { tranListToTreeData } from '@/utils/treeList'
import { getRoleDetail, assignPerm } from '@/api/settings'
export default {
  props: {
    id: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      list: []
    }
  },
  created() {
    this.loadPermissionList()
    this.loadPermissionByRoleId()
  },
  methods: {
    async loadPermissionList() {
    // 发送请求, 获取权限列表
      const { data } = await getPermissionList()
      console.log('权限列表的数据是', data)
      this.list = tranListToTreeData(data)
    },
    async loadPermissionByRoleId() {
      // 根据roleId获取当前这个角色已经具备的权限
      const res = await getRoleDetail(this.id)
      console.log('获取当前角色的已有的权限点数据', res.data.permIds)
      // 回填到树上
      this.$refs.refTree.setCheckedKeys(res.data.permIds)
    },
    hClose() {
      // 通过父组件去关闭弹层
      this.$emit('close')

      // 清空当前的选择
      this.$refs.refTree.setCheckedKeys([])
    },
    async hSubmit() {
      const permIds = this.$refs.refTree.getCheckedKeys()
      // console.log('当前选中的节点数组是', permIds)
      const res = await assignPerm({
        id: this.id,
        permIds
      })
      console.log('保存角色的权限点的结果是', res)

      // 提示
      this.$message.success('保存角色的权限成功')
      // 关闭弹层
      this.hClose()
    }
  }
}
</script>
